<template>
  <div class="admin-announcement">
    <div class="header">
      <h2>系统公告管理</h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>新增公告
      </el-button>
    </div>

    <!-- 搜索筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="公告标题">
          <el-input v-model="searchForm.title" placeholder="请输入公告标题" clearable />
        </el-form-item>
        <el-form-item label="公告类型">
          <el-select v-model="searchForm.type" placeholder="请选择公告类型" clearable>
            <el-option label="活动公告" value="activity" />
            <el-option label="系统通知" value="system" />
            <el-option label="紧急通知" value="urgent" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="有效" value="active" />
            <el-option label="失效" value="inactive" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 公告列表 -->
    <el-card>
      <el-table :data="announcementList" v-loading="loading">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="title" label="公告标题" min-width="200" />
        <el-table-column prop="type" label="公告类型" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getTypeTag(row.type)">{{ getTypeText(row.type) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="公告内容" min-width="300" show-overflow-tooltip />
        <el-table-column prop="publishTime" label="发布时间" width="180" align="center" />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'info'">
              {{ row.status === 'active' ? '有效' : '失效' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">查看</el-button>
            <el-button type="warning" size="small" @click="handleStatus(row)">
              {{ row.status === 'active' ? '设为失效' : '设为有效' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      :before-close="handleClose"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="公告标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入公告标题" />
        </el-form-item>
        <el-form-item label="公告类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择公告类型">
            <el-option label="活动公告" value="activity" />
            <el-option label="系统通知" value="system" />
            <el-option label="紧急通知" value="urgent" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="公告内容" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="6"
            placeholder="请输入公告内容"
            maxlength="1000"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="是否显示在首页" prop="showInHome">
          <el-switch v-model="form.showInHome" />
        </el-form-item>
        <el-form-item label="是否更新轮播图" prop="updateCarousel">
          <el-switch v-model="form.updateCarousel" />
        </el-form-item>
        <el-form-item v-if="form.updateCarousel" label="轮播图图片">
          <el-upload
            action="#"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleImageChange"
          >
            <el-button type="primary">选择图片</el-button>
          </el-upload>
          <div v-if="form.imageUrl" class="image-preview">
            <img :src="form.imageUrl" alt="轮播图预览" style="max-width: 200px; max-height: 120px;" />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">确定</el-button>
      </template>
    </el-dialog>

    <!-- 查看对话框 -->
    <el-dialog
      title="公告详情"
      v-model="viewDialogVisible"
      width="600px"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="公告标题">{{ currentAnnouncement.title }}</el-descriptions-item>
        <el-descriptions-item label="公告类型">
          <el-tag :type="getTypeTag(currentAnnouncement.type)">
            {{ getTypeText(currentAnnouncement.type) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="公告内容">
          <div style="white-space: pre-wrap;">{{ currentAnnouncement.content }}</div>
        </el-descriptions-item>
        <el-descriptions-item label="发布时间">{{ currentAnnouncement.publishTime }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="currentAnnouncement.status === 'active' ? 'success' : 'info'">
            {{ currentAnnouncement.status === 'active' ? '有效' : '失效' }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="viewDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const submitting = ref(false)
const formRef = ref()

// 搜索表单
const searchForm = reactive({
  title: '',
  type: '',
  status: ''
})

// 分页配置
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 公告列表
const announcementList = ref([])

// 表单数据
const form = reactive({
  title: '',
  type: '',
  content: '',
  showInHome: true,
  updateCarousel: false,
  imageUrl: ''
})

// 当前公告
const currentAnnouncement = ref({})

// 表单验证规则
const rules = {
  title: [{ required: true, message: '请输入公告标题', trigger: 'blur' }],
  type: [{ required: true, message: '请选择公告类型', trigger: 'change' }],
  content: [{ required: true, message: '请输入公告内容', trigger: 'blur' }]
}

// 计算属性
const dialogTitle = ref('新增公告')

// 方法
const getTypeText = (type) => {
  const typeMap = {
    activity: '活动公告',
    system: '系统通知',
    urgent: '紧急通知',
    other: '其他'
  }
  return typeMap[type] || '未知'
}

const getTypeTag = (type) => {
  const tagMap = {
    activity: 'success',
    system: 'primary',
    urgent: 'danger',
    other: 'info'
  }
  return tagMap[type] || 'info'
}

// 加载公告列表
const loadAnnouncements = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 模拟数据
    announcementList.value = [
      {
        id: 1,
        title: '国庆节活动通知',
        type: 'activity',
        content: '为庆祝国庆节，养老中心将于10月1日举办文艺汇演活动，欢迎各位老人及家属参加。',
        publishTime: '2024-09-28 10:00:00',
        status: 'active'
      },
      {
        id: 2,
        title: '系统维护通知',
        type: 'system',
        content: '系统将于本周六凌晨2:00-4:00进行维护，期间系统将无法访问，请提前做好准备。',
        publishTime: '2024-09-25 14:30:00',
        status: 'active'
      },
      {
        id: 3,
        title: '疫情防控紧急通知',
        type: 'urgent',
        content: '根据疫情防控要求，即日起所有访客需提供48小时内核酸检测阴性证明。',
        publishTime: '2024-09-20 09:15:00',
        status: 'inactive'
      }
    ]
    
    pagination.total = announcementList.value.length
  } catch (error) {
    ElMessage.error('加载公告列表失败：' + error.message)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadAnnouncements()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    title: '',
    type: '',
    status: ''
  })
  pagination.current = 1
  loadAnnouncements()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadAnnouncements()
}

// 当前页改变
const handleCurrentChange = (current) => {
  pagination.current = current
  loadAnnouncements()
}

// 新增公告
const handleAdd = () => {
  dialogTitle.value = '新增公告'
  Object.assign(form, {
    title: '',
    type: '',
    content: '',
    showInHome: true,
    updateCarousel: false,
    imageUrl: ''
  })
  dialogVisible.value = true
}

// 查看公告
const handleView = (row) => {
  currentAnnouncement.value = { ...row }
  viewDialogVisible.value = true
}

// 修改状态
const handleStatus = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要${row.status === 'active' ? '设为失效' : '设为有效'}该公告吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 300))
    
    ElMessage.success('状态修改成功')
    loadAnnouncements()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('状态修改失败：' + error.message)
    }
  }
}

// 图片选择
const handleImageChange = (file) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    form.imageUrl = e.target.result
  }
  reader.readAsDataURL(file.raw)
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  formRef.value?.resetFields()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    ElMessage.success(dialogTitle.value === '新增公告' ? '新增成功' : '编辑成功')
    dialogVisible.value = false
    loadAnnouncements()
  } catch (error) {
    if (error.errors) {
      ElMessage.error('请完善表单信息')
    } else {
      ElMessage.error('操作失败：' + error.message)
    }
  } finally {
    submitting.value = false
  }
}

// 生命周期
onMounted(() => {
  loadAnnouncements()
})
</script>

<style scoped>
.admin-announcement {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.image-preview {
  margin-top: 10px;
  padding: 10px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #f5f7fa;
}
</style>
